package leetcode2;

import java.util.LinkedList;
import java.util.Queue;

public class AverageOfSubtree {
    int ans = 0;

    public int averageOfSubtree(TreeNode root) {
        if (root != null) {
            int[] s = statistics(root);
            int avg = s[1] / s[0];
            if (avg == root.val) {
                ans++;
            }
            averageOfSubtree(root.left);
            averageOfSubtree(root.right);
        }
        return ans;
    }

    public int[] statistics(TreeNode root) {
        // 0:个数 1:和
        int[] res = new int[2];
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            res[0]++;
            res[1] += node.val;
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        return res;
    }
}
